//
//  DHPicView.m
//  发;fjag
//
//  Created by 刘鹏飞 on 2016/11/14.
//  Copyright © 2016年 刘鹏飞. All rights reserved.
//

#import "DHPicView.h"
#import <Masonry.h>

@interface DHPicView ()


@property (nonatomic,strong)NSMutableArray *images;

@end

@implementation DHPicView

+(instancetype)picView {
    
    DHPicView *picView = [[DHPicView alloc] init];
    
    //添加子控件
    UILabel *picLabel = [UILabel XHH_labelWithText:@"病例图片:" fontSize:15 color:[UIColor blackColor]];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"AddPic"]];
    imageView.userInteractionEnabled = YES;
    picView.addImage = imageView;
    picView.imageArrOne = [NSMutableArray array];
    picView.images = [NSMutableArray array];
    
    //添加到父控件
    [picView addSubview:picLabel];
    [picView addSubview:imageView];
    
    //约束
    [picLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(picView).offset(20);
        make.left.equalTo(picView).offset(8);
    }];
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    imageView.frame = CGRectMake((width-330)*0.25, 50, 110, 110);
    return picView;
}


//重写属性的setter方法
-(void)setImageArr:(NSArray *)imageArr {
    
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    for (UIImageView * imgView in self.imageArrOne) {
        [imgView removeFromSuperview];
    }
    _imageArr = imageArr;
    NSMutableArray *arrM = [NSMutableArray array];
    for (int i = 0; i < imageArr.count; i++) {
        [arrM addObject:imageArr[i]];
    }
    self.images = arrM;
    
    for (int i = 0; i < imageArr.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:imageArr[i]];
        [self addSubview:imageView];
        UIButton *btn = [[UIButton alloc] init];
        btn.tag = i;
        [btn setImage:[UIImage imageNamed:@"deleteicon"] forState:UIControlStateNormal];
        [imageView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(imageView).offset(5);
            make.right.equalTo(imageView.mas_right).offset(-5);
            make.size.mas_equalTo(CGSizeMake(20, 20));
        }];
        [btn addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
        [self.imageArrOne addObject:imageView];
        imageView.frame = CGRectMake(((width-330)*0.25)*(i+1)+110*i, 50, 110, 110);
        self.addImage.frame = CGRectMake(((width-330)*0.25)*(i+2)+110*(i+1), 50, 110, 110);
        
    }
    self.myTapBlock(self.imageArrOne);
}

//删除照片
-(void)deleteImage:(UIButton *)sender {
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    [self.images removeObjectAtIndex:sender.tag];
    if (self.images.count == 0) {
        self.addImage.frame = CGRectMake((width-330)*0.25, 50, 110, 110);
    }
    self.imageArr = self.images;
}

@end
